# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 电信客户流失预测.py
# @Author: dongguangwen
# @Date  : 2025-02-07 11:15
# 0.导包
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score, classification_report


# 1.数据处理
data = pd.read_csv('./data/churn.csv')
# print(data.info())
# print(data.head())

data = pd.get_dummies(data)  # 处理类别型的数据 类别型数据做one-hot编码
# print(data.head())

data = data.drop(['Churn_No', 'gender_Male'], axis=1)  # 去除列 Churn_no gender_Male
# print(data.head())

data = data.rename(columns={'Churn_Yes': 'flag'})  # 列标签重命名
print(data.head())
print(data.flag.value_counts())

# 2.特征工程
sns.countplot(data=data, y='Contract_Month', hue='flag')  # 看Contract_Month 是否月签约流失情况
plt.show()

x = data[['PaymentElectronic', 'Contract_Month', 'internet_other']]
y = data['flag']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=22)

# 3.模型训练
model = LogisticRegression()
model.fit(x_train, y_train)
print('参数：', model.coef_)

# 4.模型评估
y_pred = model.predict(x_test)

print("Accuracy:", accuracy_score(y_test, y_pred))
print("ROC AUC Score:", roc_auc_score(y_test, y_pred))  # 使用概率值计算 ROC AUC
print("Classification Report:\n", classification_report(y_test, y_pred))

"""
   Partner_att  Dependents_att  landline  ...  TotalCharges   flag  gender_Female
0            1               0         0  ...         29.85  False           True
1            0               0         1  ...       1889.50  False          False
2            0               0         1  ...        108.15   True          False
3            0               0         0  ...       1840.75  False          False
4            0               0         1  ...        151.65   True           True

[5 rows x 16 columns]
flag
False    5174
True     1869
Name: count, dtype: int64
参数： [[0.67559062 1.99870723 0.99623951]]
Accuracy: 0.7615330021291696
ROC AUC Score: 0.6525982915343336
Classification Report:
               precision    recall  f1-score   support

       False       0.79      0.90      0.84      1012
        True       0.62      0.40      0.49       397

    accuracy                           0.76      1409
   macro avg       0.71      0.65      0.67      1409
weighted avg       0.74      0.76      0.74      1409
"""